<template>
  <div>
    <el-form inline>
      <el-form-item label="分组依据">
        <el-checkbox-group v-model="group.by" @change="doAnalysis">
          <el-checkbox-button label="deviceId">储物柜</el-checkbox-button>
          <el-checkbox-button label="deviceIndex">储物仓</el-checkbox-button>
          <el-checkbox-button label="key">凭证</el-checkbox-button>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="分析指标">
        <el-checkbox-group v-model="group.value" @change="doAnalysis">
          <el-checkbox-button label="count">次数</el-checkbox-button>
          <el-checkbox-button label="minute">时长</el-checkbox-button>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    <div ref="chart" style="width: 90vw;height: 45vh;"></div>
    <div>{{ result }}</div>
  </div>
</template>
<script>
  import deviceAnalysisAPI from '@/api/device/analysis'
  import * as echarts from 'echarts'
  import ListAnalysis from '@/utils/ListAnalysis'
  const options = {
    title: {
      text: '自定义图谱',
    },
    tooltip: {
      show: true
    },
    xAxis: [{
      type: 'category'
    }],
    yAxis: [{
      type: 'value'
    }],
    series: [{
      type: 'bar'
    }]
  }
  export default {
    name: 'CustomBar',
    data() {
      return {
        chart: null,
        group: {
          by: [],
          value: []
        },
        permissions: [],
        result: {
          map: {},
          list: []
        }
      }
    },
    created() {},
    mounted() {
      this.queryPermission()
      setTimeout(this.createChart, 300)
    },
    methods: {
      queryPermission() {
        const vm = this
        deviceAnalysisAPI.permissionList({
          startDate: null,
          endDate: null
        }).then(res => {
          vm.permissions = [].concat(res.data)
        })
      },
      doAnalysis() {
        if (this.group.by.length === 0 || this.group.value.length === 0) {
          return
        }
        const analysis = new ListAnalysis(this.permissions)
        this.result = analysis.groupBy(this.group.by, this.group.value)
        this.updateChart()
      },
      createChart() {
        const el = this.$refs['chart']
        this.chart = echarts.init(el);
        this.chart.setOption(options)
        this.updateChart();
      },
      updateChart() {
        const {
          by,
          value,
        } = this.group
        if (this.chart === null) {
          return
        }
        const dimensions = [by.join('-')]
        for (var i = 0; i < value.length; i++) {
          dimensions.push(value[i] + '-sum')
        }
        const {
          list,
          map
        } = this.result
        this.chart.setOption({
          dataset: [{
            dimensions,
            source: list
          }]
        });
      }
    }
  }

</script>
